/********************************************************************/
/*  Copyright (C) SSE-USTC, 2013                                    */
/*                                                                  */
/*  FILE NAME             :  write_shmem.c                          */
/*  PRINCIPAL AUTHOR      :  Tangxingyu                             */
/*  SUBSYSTEM NAME        :  test fo Debug                          */
/*  MODULE NAME           :  Debug                                  */
/*  LANGUAGE              :  C                                      */
/*  TARGET ENVIRONMENT    :  Linux                                  */
/*  DATE OF FIRST RELEASE :  2013/6/12                              */
/*  DESCRIPTION           :  test for write to shmem                */
/********************************************************************/

/*
 * Revision log:
 *
 * Created by Tangxingyu ,2013/6/12
 *
 */

#include <stdio.h>
typedef unsigned char u_char;
typedef unsigned int u_int;

int write_mail_shmem(int res, mailinfo * mailhp,char * subject, char * text)
{
	struct mail_head_shmem mhmem;
	u_char * mhead_mem = NULL;
	u_char * mtext_mem = NULL;
	u_int sublen = 0;
	u_int textlen = 0;
	u_int rest = 0;
	u_int totallen = 0;

	rest = (u_int)res;
	sublen = (u_int)strlen(subject);
	textlen = (u_int)strlen(text);
	totallen = sublen + textlen;
	printf("totallen is %u\n",totallen);
	mhead_mem = (u_char*)malloc(20*sizeof(char)); //malloc mailhead for write to sharemem
	assert(mhead_mem != NULL);

	memset(mhead_mem,0,20);
	memcpy(mhead_mem,&(mailhp->sorip),4);
	memcpy(mhead_mem+4,&(mailhp->desip),4);
	memcpy(mhead_mem+8,&(mailhp->sorport),2);
	memcpy(mhead_mem+10,&(mailhp->desport),2);
	memcpy(mhead_mem+12,&totallen,4);
	memcpy(mhead_mem+16,&rest,4);

	mtext_mem = (u_char*)malloc((8+totallen)*sizeof(char));
	assert(mtext_mem != NULL);
	memset(mtext_mem,0,8+totallen);
	memcpy(mtext_mem,&sublen,4);
	memcpy(mtext_mem+4,&filelen,4);
	memcpy(mtext_mem+8,subject,sublen);
	memcpy(mtext_mem+8+sublen,text,textlen);

	//begin to write to shmem
	while(fuckwrite(&m_smptr,mhead_mem,20,m_semid)!=0)
	{
		printf("write to mem wait1\n");
		sleep(1);
	}
	while(fuckwrite(&m_smptr,mtext_mem,totalen+8,m_semid)!=0)
	{
		printf("write to mem wait2\n");
		sleep(1);
	}
	printf("write mem OK\n");
	free(mhead_mem);
	mhead_mem = NULL;
	free(mtext_mem);
	mtext_mem = NULL;
	printf("free tmp mem OK\n");
	return 0;
}